const mysql = require('mysql')
const dbConfig = require('./db')
const sqlMap = require('./sqlMap')
const jwt = require('jsonwebtoken')

const pool = mysql.createPool({
  host: dbConfig.mysql.host,
  user: dbConfig.mysql.user,
  password: dbConfig.mysql.password,
  database: dbConfig.mysql.database,
  port: dbConfig.mysql.port,
  multipleStatements: true
})

module.exports = {
  upload(req, res, next) {
    const pathName = 'uploads/' + req.file.filename
    res.json({ errcode: 0, errmsg: '上传成功', data: pathName })
  },
  register(req, res, next) {
    const params = req.body
    pool.getConnection((_err, connection) => {
      const sqlInsert = sqlMap.updateUser

      // 查询数据库中是否已经存在用户名
      const checkAccountAndUser = sqlMap.checkAccountAndUser
      connection.query(checkAccountAndUser, [params.userName], (_err, result) => {
        if (result && result.length !== 0) {
          if (result.indexOf(params.userName) !== -1) {
            res.json({ errcode: 400, errmsg: '用户名已存在', data: '' })
          } else if (result.indexOf(params.account) !== -1) {
            res.json({ errcode: 400, errmsg: '账号已存在', data: '' })
          }
        } else {
          connection.query(sqlInsert, [params.avatar, params.account, params.userName, params.password], (_err, result) => {
            res.json({ errcode: 0, errmsg: '注册成功' })
          })
        }
        connection.release()
      })
    })
  },
  login(req, res, next) {
    const params = req.body
    const token = jwt.sign(
      {
        account: params.account
      },
      'azrael',
      { expiresIn: 60 * 60 * 24 }
    )
    pool.getConnection((_err, connection) => {
      const loginSql = sqlMap.loginSql
      connection.query(loginSql, [params.account, params.password], (_err, result) => {
        if (result.length === 0) {
          res.json({ errcode: 400, errmsg: '账号或者密码错误', data: '' })
        } else {
          res.json({ errcode: 0, errmsg: '验证成功', data: { token, ...result[0] } })
        }
        connection.release()
      })
    })
  },
  getUserInfo(req, res, next) {
    const token = req.query.token
    jwt.verify(token, 'azrael', (err, decode) => {
      if (err) {
        res.json({ errcode: 401, errmsg: 'token失效，请重新登陆' })
      } else {
        pool.getConnection((_err, connection) => {
          const sql = `SELECT * FROM user WHERE account = ?`
          connection.query(sql, [decode.account], (_err, result) => {
            res.json({ errcode: 0, errmsg: '', data: { ...result[0] } })
            connection.release()
          })
        })
      }
    })
  },
  getArticleList(req, res, next) {
    pool.getConnection((_err, connection) => {
      const getArticleListSql = sqlMap.getArticleList
      connection.query(getArticleListSql, [], (_err, result) => {
        const arr = result.map((item) => {
          return {
            ...item,
            article_desc: item.article_content.slice(0, 100)
          }
        })
        res.json({ errcode: 0, data: arr, errmsg: '' })
        connection.release()
      })
    })
  },
  addArticle(req, res, next) {
    const params = req.body
    pool.getConnection((_err, connection) => {
      const addArticleSql = sqlMap.addArticle
      connection.query(addArticleSql, [params.article_title, params.article_content, params.userId, params.name], (_err, result) => {
        res.json({ errcode: 0, errmsg: '发表成功' })
        connection.release()
      })
    })
  }
}
